package worker

import (
	"distributed/message"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var normalTick = time.Tick(time.Second * 3)

func normalClient(method, url string, body url.Values) ([]byte, error) {
	<-normalTick
	req, err := http.NewRequest(method, url, strings.NewReader(body.Encode()))
	if err != nil {
		fmt.Println("[ http.NewRequest(task.Method, task.URL, nil) ] error: ", err)
		return nil, err
	}

	req.Header.Add("User-Agent", getUserAgent())
	req.Header.Add("Host", "music.163.com")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		resultChan <- message.ReptileResult{
			ReptileReq: message.ReptileReq{
				Method: method,
				URL:    url,
			},
			ReptileResp: message.ReptileResp{
				Status: 200,
			},
		}
		fmt.Println("[ http.DefaultClient.Do(req) ] error: ", err)
		return nil, err
	}
	defer resp.Body.Close()

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		resultChan <- message.ReptileResult{
			ReptileReq: message.ReptileReq{
				Method: method,
				URL:    url,
			},
			ReptileResp: message.ReptileResp{
				HttpStatus: resp.StatusCode,
				Status:     200,
			},
		}
		fmt.Println("[ ioutil.ReadAll(resp.Body) ] error: ", err)
		return nil, err
	}
	return respBytes, nil
}
